﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Model.Common;
using br.com.SistemaChamados.Util;
using System.Web.Security;


namespace SistemaChamados.Pages.Common
{
    public partial class Login : System.Web.UI.Page
    {
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            br.com.SistemaChamados.Model.Common.User user =
                new br.com.SistemaChamados.Model.Common.User();
            user.EMail = txbLogin.Text;
            user.Password = txbPassword.Text;
            UserController userController = new UserController();
            try
            {
                if (userController.validateUser(ref user) == EnumUserState.USER_STATE_LOGGED_IN)
                {
                    Response.Cookies.Add(SecurityUtils.createATicketValidation(user));
                    string returnUrl = Request.QueryString["ReturnUrl"];
                    Response.Redirect(returnUrl);
                    Response.Write(@"<script language='javascript'>alert('Usuário OK!');</script>");
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Usuário inexistente!');</script>");
                }
            }
            catch (Exception ex)
            {
                //TODO arrancar javascript e criar página de erro
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao validar o login: <br>" + ex.Message +
                               ".');</script>");
                user = null;
            }
        }

        protected void btnInserir_Click(object sender, EventArgs e)
        {
            if (ddlSector.SelectedIndex == 0)
            {
                Response.Write(@"<script language='javascript'>alert('Selecione um setor');</script>");
                ddlSector.Focus();
            }
            else
            {
                if (ddlUnit.SelectedIndex == 0)
                {
                    Response.Write(@"<script language='javascript'>alert('Selecione uma unidade');</script>");
                    ddlUnit.Focus();
                }
                else
                {
                    User userInsert = new User();
                    userInsert.Sector = new Sector();
                    userInsert.EMail = txbEMail.Text;
                    userInsert.Name = txbName.Text;
                    userInsert.Password = txbPassword.Text;
                    userInsert.Sector.Id = Convert.ToInt32(ddlSector.SelectedValue);
                    tryInsert(userInsert);
                }
            }
        }

        private void tryInsert(User userInsert)
        {
            UserController controller = new UserController();
            try
            {
                if (controller.InsertUser(userInsert) == EnumGenericState.GENERIC_STATE_SUCCESS)
                {
                    Response.Write(@"<script language='javascript'>alert('Pessoa Cadastrada com Sucesso!');</script>");
                    ClearFields();
                    ClearDdlSector();
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante o cadastro, por favor tente novamente!');</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no cadastro: <br>" + ex.Message +
                                   ".');</script>");
                userInsert = null;
            }
        }

        private void ClearFields()
        {
            txbName.Text = "";
            txbEMail.Text = "";
            txbPassword.Text = "";
            txbPasswordValidate.Text = "";
            txbName.Focus();
        }

        private void FillDdlUnit()
        {
            UnitController unitController = new UnitController();
            ddlUnit.DataSource = unitController.GetUnits();
            ddlUnit.DataTextField = "Name";
            ddlUnit.DataValueField = "Id";
            ddlUnit.DataBind();
            ddlUnit.Items.Insert(0, "Selecione");
        }
        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillDdlSector();
        }

        private void ClearDdlSector()
        {
            for (int i = 0; i < ddlSector.Items.Count; i++)
            {
                ddlSector.Items[i].Selected = false;
            }
            ddlSector.Items[0].Selected = true;
            ddlSector.DataSource = "";
            ddlSector.DataBind();
        }

        private void FillDdlSector()
        {
            SectorController sectorController = new SectorController();
            br.com.SistemaChamados.Model.Unit unit = new br.com.SistemaChamados.Model.Unit();
            Sector sector = new Sector();
            if (Convert.ToInt32(ddlUnit.SelectedIndex) != 0)
            {
                unit.Id = Convert.ToInt32(ddlUnit.SelectedValue);
                sector.Unit = unit;
                ddlSector.DataSource = sectorController.ListSectorByUnit(sector);
                ddlSector.DataTextField = "Description";
                ddlSector.DataValueField = "Id";
                ddlSector.DataBind();
                ddlSector.Items.Insert(0, "Selecione");
            }
            else
            {
                ClearDdlSector();
            }

        }
    }
}